﻿using Learun.Application.Base.SystemModule;
using Learun.Application.TwoDevelopment.ZZDT_EC;
using Learun.Util;
using log4net.Config;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;

namespace Learun.Application.Web.AppApi
{
    /// <summary>
    /// 图纸文件接口
    /// </summary>
    [RoutePrefix("api/DrawingFileApi")]
    [HandlerApiLogin(FilterMode.Enforce)]
    [TokenAuthorize]
    public class DrawingFileApiController : WebApiControllerBase
    {
        private ec_drawing_catalogueBLL ec_drawing_catalogueIBLL = new ec_drawing_catalogueBLL();
        private ec_drawing_fileBLL ec_drawing_fileIBLL = new ec_drawing_fileBLL();
        private ec_drawing_synIBLL ec_drawing_synIBLL = new ec_drawing_synBLL();
        private ec_drawing_publishIBLL ec_drawing_publishIBLL = new ec_drawing_publishBLL();
        private ec_operate_logIBLL ec_operate_logIBLL = new ec_operate_logBLL();
        private AnnexesFileIBLL annexesFileIBLL = new AnnexesFileBLL();
        private ec_dataitemIBLL dataItemIBLL = new ec_dataitemBLL();
        private ec_enginedataIBLL ec_enginedataIBLL = new ec_enginedataBLL();
        private ec_enginedata_pixelIBLL pixelBll = new ec_enginedata_pixelBLL();
        /// <summary>
        /// 获取图纸目录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="onlyFolderFlag">是否只查询文件夹。1代表只查询文件夹</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(List<TreeModel>))]
        public IHttpActionResult GetDrawingCatalogue(string projectId, string onlyFolderFlag)
        {
            try
            {
                var res = ec_drawing_catalogueIBLL.GetDrawingCategory(projectId, onlyFolderFlag);
                return Success(res);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取图纸类型目录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(List<TreeModel>))]
        public IHttpActionResult GetDrawingCatalogueByType(string projectId)
        {
            try
            {
                var treeList = ec_drawing_catalogueIBLL.GetDrawingCategoryByType(projectId);
                return Success(treeList);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取图纸所属系统目录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(List<TreeModel>))]
        public IHttpActionResult GetDrawingCatalogueBySystem(string projectId)
        {
            try
            {
                var treeList = ec_drawing_catalogueIBLL.GetDrawingCatalogueBySystem(projectId);
                return Success(treeList);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取图纸文件信息
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpGet]
        [ResponseType(typeof(ec_drawing_fileEntity))]
        public IHttpActionResult GetEntity(string projectId, string drawingFileID)
        {
            try
            {
                var entity = ec_drawing_fileIBLL.GetEntity(drawingFileID, projectId);
                var fileList = annexesFileIBLL.GetList(entity.FolderId).ToList();
                if (fileList != null && fileList.Count > 0)
                {
                    entity.FileId = fileList[0].F_Id;
                }
                return Success(entity);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }




        /// <summary>
        /// 新增图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult AddDrawingFile(string projectId)
        {
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                ec_drawing_fileEntity entity = asyncContent.ToObject<ec_drawing_fileEntity>();

                //同一目录下不允许有名称相同的图纸文件
                var data = ec_drawing_fileIBLL.GetList("{DrawingCatalogueID:\"" + entity.DrawingCatalogueID + "\",\"ProjectId\":\"" + projectId + "\",DrawingFileNameFull:\"" + entity.DrawingFileName + "\"}").ToList();
                if (data != null && data.Count > 0)
                {
                    return Fail("同一目录下不允许有名称相同的图纸文件！");
                }
                entity.Create();
                //默认参数
                entity.IsPublish = 0;
                entity.IsCheckOut = 1;
                entity.CheckOutUserID = entity.CreateUserID;
                entity.CheckOutTime = entity.CreateTime;
                ec_drawing_fileIBLL.InertEntity(entity, projectId);
                return Success(entity);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 编辑图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult EditDrawingFile(string projectId)
        {
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                ec_drawing_fileEntity entity = asyncContent.ToObject<ec_drawing_fileEntity>();
                //同一目录下不允许有名称相同的图纸文件
                var data = ec_drawing_fileIBLL.GetList("{DrawingCatalogueID:\"" + entity.DrawingCatalogueID + "\",\"ProjectId\":\"" + projectId + "\",DrawingFileNameFull:\"" + entity.DrawingFileName + "\",DrawingFileIDUnequal:\"" + entity.DrawingFileID + "\"}").ToList();
                if (data != null && data.Count > 0)
                {
                    return Fail("同一目录下不允许有名称相同的图纸文件！");
                }
                ec_drawing_fileEntity entityOld = ec_drawing_fileIBLL.GetEntity(entity.DrawingFileID, projectId);
                entity.IsPublish = entityOld.IsPublish;
                entity.IsCheckOut = entityOld.IsCheckOut;
                entity.CheckOutUserID = entityOld.CheckOutUserID;
                entity.CheckOutTime = entityOld.CheckOutTime;
                ec_drawing_fileIBLL.EditEntity(entity, projectId);
                return Success("编辑成功");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 删除图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteDrawingFile(string projectId, string drawingFileID)
        {
            try
            {
                var entity = ec_drawing_fileIBLL.GetEntity(drawingFileID, projectId);
                if (entity?.IsEngineDWG == 1)
                {
                    ec_drawing_fileIBLL.LogicDelete(drawingFileID, projectId);
                }
                else
                {
                    ec_drawing_fileIBLL.DeleteEntity(drawingFileID, projectId);
                }
                return Success("删除成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 检出图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CheckOutDrawingFile(string projectId, string drawingFileID)
        {
            try
            {
                ec_drawing_fileIBLL.CheckOutDrawingFile(drawingFileID, projectId);
                return Success("检出成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 预检入，生成一些自动生成的增删改内容（By YuXH）。配合<see cref="CheckInDrawingFile(string, string, string, string, string, string)"/>，放在其前面
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="drawingFileID"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult PreCheckInDrawingFile(string projectId, string drawingFileID)
        {
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                //List<ec_enginedata_pixelEntity> entityList = asyncContent.ToList<ec_enginedata_pixelEntity>();
                var pixelBLL = new ec_enginedata_pixelBLL();
                pixelBLL.Clear(drawingFileID, projectId);
                //string res = new ec_notificationBLL().GenerateCompareRes(entityList, projectId, drawingFileID); 暂时取消，内容不太合适。
                return Success("");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 检入图纸文件（句柄信息）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="folderId">文件夹ID</param>
        /// <param name="fileMD5">文件MD5</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CheckInDrawingFileNew(string projectId, string drawingFileID, string folderId, string fileMD5)
        {
            //如何避免数据丢失
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                List<ec_enginedata_pixelEntity> entityList = asyncContent.ToList<ec_enginedata_pixelEntity>();
                if (entityList == null || entityList.Count == 0)
                {
                    //避免前端因频繁切换图纸造成检入时，一个都没有，而把数据库里的都清空了
                    XmlConfigurator.Configure();
                    var log = log4net.LogManager.GetLogger("INFO"); //参数就是config里logger节点的名字
                    log.Error($"★★★{DateTime.Now.ToString()}★★★Drawing Check In Only 0 Pixel【DrawingId:{drawingFileID}】★★★");
                    //return Success("检入成功！");
                    //entityList = new List<ec_enginedata_pixelEntity>();
                }
                else if (string.IsNullOrEmpty(folderId))
                {
                    log4net.LogManager.GetLogger("ERROR").Error("检入图纸 - " + "无效的空白FolderId");
                    throw new Exception("检入图纸 - " + "无效的空白FolderId");
                }
                else
                {
                    pixelBll.SavePixels(entityList, projectId, drawingFileID);

                }

                return Success("检入成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 检入图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="remark">描述</param>
        /// <param name="folderId">文件夹ID</param>
        /// <param name="fileMD5">文件MD5</param>
        /// <param name="UsersNotified">待通知的用户，逗号分隔</param>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public IHttpActionResult CheckInDrawingFile(string projectId, string drawingFileID, string remark, string folderId, string fileMD5, string UsersNotified)
        {
            //如何避免数据丢失
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                List<ec_enginedata_pixelEntity> entityList = asyncContent.ToList<ec_enginedata_pixelEntity>();
                if (entityList == null || entityList.Count == 0)
                {
                    //避免前端因频繁切换图纸造成检入时，一个都没有，而把数据库里的都清空了
                    XmlConfigurator.Configure();
                    var log = log4net.LogManager.GetLogger("INFO"); //参数就是config里logger节点的名字
                    log.Error($"★★★{DateTime.Now.ToString()}★★★Drawing Check In Only 0 Pixel【DrawingId:{drawingFileID}】★★★");
                    //return Success("检入成功！");
                    //entityList = new List<ec_enginedata_pixelEntity>();
                }
                else if (string.IsNullOrEmpty(folderId))
                {
                    log4net.LogManager.GetLogger("ERROR").Error("检入图纸 - " + "无效的空白FolderId");
                    throw new Exception("检入图纸 - " + "无效的空白FolderId");
                }
                else
                {
                    pixelBll.SavePixels(entityList, projectId, drawingFileID);

                }
                //换了下顺序，先SaveMuliteEntity，再CheckInDrawingFile。这样就算SaveMuliteEntity报错了，但是图纸至少不会被检入，免得出现之前数据丢失的问题
                ec_drawing_fileIBLL.CheckInDrawingFile(drawingFileID, remark, folderId, fileMD5, projectId, UsersNotified);

                return Success("检入成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
        /// <summary>
        /// 检入图纸文件（修改消息）
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param> 
        /// <param name="folderId">文件夹ID</param>
        /// <param name="fileMD5">文件MD5</param>
        /// <param name="UsersNotified">待通知的用户，逗号分隔</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CheckInDrawingMsg(string projectId, string drawingFileID, string folderId, string fileMD5, string UsersNotified)
        {
            //如何避免数据丢失
            try
            {
                var httpContent = Request.Content;
                var asyncContent = httpContent.ReadAsStringAsync().Result;
                var x = asyncContent.ToJObject();
                x.TryGetValue("data", out JToken value);
                ec_drawing_synEntity Msg = value.ToString().ToObject<ec_drawing_synEntity>();
                if (Msg != null)
                {
                    Msg.DrawingFileID = drawingFileID;
                    Msg.FolderId = folderId;
                    ec_drawing_fileIBLL.CheckInDrawingFileNew( Msg, fileMD5, projectId, UsersNotified);
                }

                return Success("保存成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 释放图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult FreeDrawingFile(string projectId, string drawingFileID)
        {
            try
            {
                ec_drawing_fileIBLL.FreeDrawingFile(drawingFileID, projectId);
                return Success("释放成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 发布图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        ///  <param name="remark">备注</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult PublishDrawingFile(string projectId, string drawingFileID, string remark)
        {
            try
            {
                ec_drawing_fileIBLL.PublishDrawingFile(drawingFileID, remark, projectId);
                return Success("发布成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 修订图纸文件
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <param name="fileVersion">版本</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult ModifyDrawingFile(string projectId, string drawingFileID, string fileVersion)
        {
            try
            {
                ec_drawing_fileIBLL.ModifyDrawingFile(drawingFileID, fileVersion, projectId);
                return Success("修订成功！");
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取单个图纸的检入记录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetCheckInLog(string projectId, string drawingFileID)
        {
            try
            {
                string queryJson = "{\"DrawingFileID\":\"" + drawingFileID + "\",\"ProjectId\":\"" + projectId + "\"}";
                var listDrawingSyn = ec_drawing_synIBLL.GetList(queryJson);
                return Success(listDrawingSyn);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取发布记录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetPublishLog(string projectId, string drawingFileID)
        {
            try
            {
                string queryJson = "{\"DrawingFileID\":\"" + drawingFileID + "\",\"ProjectId\":\"" + projectId + "\"}";
                var listDrawingPublish = ec_drawing_publishIBLL.GetList(queryJson);
                return Success(listDrawingPublish);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }

        /// <summary>
        /// 获取操作记录
        /// </summary>
        /// <param name="projectId">项目ID</param>
        /// <param name="drawingFileID">图纸文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult GetOperateLog(string projectId, string drawingFileID)
        {
            try
            {
                string queryJson = "{\"OwnerID\":\"" + drawingFileID + "\",\"ProjectId\":\"" + projectId + "\"}";
                var listlog = ec_operate_logIBLL.GetList(queryJson);
                return Success(listlog);
            }
            catch (Exception ex)
            {
                return Fail(ex.Message);
            }
        }
    }
}